package com.example.demo;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "contextFilter")
public class ContextFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    /**
     * 支持 jsonp 以及一部分 非 controller 的 http访问的 权限检查
     *
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        MyHttpServletResponseWrapper myResp = new MyHttpServletResponseWrapper((HttpServletResponse) resp);
        chain.doFilter(req, myResp);

        HttpServletRequest request = (HttpServletRequest) req;
        LogInfoBean logEntity = new LogInfoBean(getIpAddr(request), request);

        log.info(
                "\nBEGIN -------------------> \n" +
                        "path ==============\n {} \n" +
                        "re ==============\n {}\n" +
                        "head ==============\n {}\n" +
                        "time ==============\n {}\n" +
                        "END ------------------->",
                logEntity.getUri(),
                myResp.toString(),
                logEntity.getHeads(),
                logEntity.getTime()
        );
    }

    public static String getIpAddr(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.length() > 24) {
            String[] ips=ip.split(",");
            ip=ips[0];
        }
        return ip;
    }


    @Override
    public void destroy() {

    }
}
